import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Address } from './address.entity';
import { CreateAddressDto } from './dto/create-address.dto';
import { UpdateAddressDto } from './dto/update-address.dto';

@Injectable()
export class AddressService {
  constructor(
    @InjectRepository(Address)
    private addressRepository: Repository<Address>,
  ) {}

  // 创建地址（关联用户ID）
  async create(createAddressDto: CreateAddressDto): Promise<Address> {
    const address = this.addressRepository.create(createAddressDto);
    return this.addressRepository.save(address);
  }

  // 获取用户所有地址（按 userId 过滤）
  async findAll(userId: number): Promise<Address[]> {
    return this.addressRepository.find({
      where: { userId },
    });
  }

  // 获取单个地址（按 ID）
  async findOne(id: number): Promise<Address> {
    const address = await this.addressRepository.findOne({ where: { id } });
    if (!address) {
      throw new NotFoundException('地址不存在');
    }
    return address;
  }

  // 更新地址（验证用户权限）
  async update(id: number, userId: number, updateAddressDto: UpdateAddressDto): Promise<Address> {
    const address = await this.findOne(id);
    if (address.userId !== userId) {
      throw new BadRequestException('无权限修改此地址');
    }
    Object.assign(address, updateAddressDto);
    return this.addressRepository.save(address);
  }

  // 删除地址（验证用户权限）
  async remove(id: number, userId: number): Promise<void> {
    const address = await this.findOne(id);
    if (address.userId !== userId) {
      throw new BadRequestException('无权限删除此地址');
    }
    await this.addressRepository.remove(address);
  }
}